package com.example.musicplayer.controller;

import com.example.musicplayer.mapper.UserMapper;
import com.example.musicplayer.model.User;
import com.example.musicplayer.tools.Constant;
import com.example.musicplayer.tools.ResponseBodyMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/login")
    public ResponseBodyMessage<User> login(@RequestParam String username,
                                           @RequestParam String password,
                                           HttpServletRequest request){
//        User userLogin = new User();
//        userLogin.setUsername(username);
//        userLogin.setPassword(password);
//
//        User user = userMapper.login(userLogin);

        User user = userMapper.selectByName(username);

        if (user != null){
            boolean flag = bCryptPasswordEncoder.matches(password, user.getPassword());
            if (!flag){
                return new ResponseBodyMessage<>(0, "用户名或密码错误！", user);
            }
            System.out.println("登陆成功!");
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY, user);
            return new ResponseBodyMessage<>(1, "登陆成功！", user);
        }else {
            System.out.println("登陆失败!");
            return new ResponseBodyMessage<>(0, "登陆失败！", user);
        }
    }

    @RequestMapping("/register")
    public ResponseBodyMessage<User> register(@RequestParam String username,
                                              @RequestParam String password,
                                              HttpServletRequest request){
        User user = userMapper.selectByName(username);
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String newPassword = bCryptPasswordEncoder.encode(password);
        if (user != null){
            return new ResponseBodyMessage<>(0, "用户名已被注册", user);
        }
        boolean reg = userMapper.insert(username, newPassword);
        if (reg){
            return new ResponseBodyMessage<>(1, "注册成功", user);
        }
        return new ResponseBodyMessage<>(0, "注册失败", user);
    }
}
